package com.able.concurrency.t1;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author abel.he
 * @data 2018/8/15 20:06
 * @describe 门闩：可以和锁混合使用，或替代锁的功能。
 * 在门闩未开放之前等待，当门闩完全开放后执行
 * 避免锁的效率低下问题
 */
public class Test15 {

    CountDownLatch latch = new CountDownLatch(5);

    void m1() {
        try {
            latch.await(); //等待门闩释放完毕
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m1 method");
    }

    void m2() {
        for (int i = 0; i < 10; i++) {
            if (latch.getCount() != 0) {
                System.out.println("latch count: " + latch.getCount());
                latch.countDown(); //减门闩数量
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("m2 method: " + i);
        }
    }

    public static void main(String[] args) {
        final Test15 test15 = new Test15();
        new Thread(new Runnable() {
            public void run() {
                test15.m1();
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                test15.m2();
            }
        }).start();
    }

}
